#!/bin/bash
script_path=$(cd "$(dirname "$0")" && pwd)
git_proxy=https://mirror.ghproxy.com/
prom_version=2.51.1
pre_path=/opt/prometheus
prom_url=https://github.com/prometheus/prometheus/releases/download/v${prom_version}/prometheus-${prom_version}.linux-amd64.tar.gz
command -v jq >>/dev/null && country=$(curl -s https://ipinfo.io/$(curl ifconfig.me) | jq -r ".country") || country=$(curl -s https://ipinfo.io/$(curl ifconfig.me) | grep country | awk -F '"' '{print $4}')

prom_download() {
  if [ "$country" == "CN" ]; then
    curl -O ${git_proxy}${prom_url}
  else
    curl -O ${prom_url}
  fi
}

prom_install() {
  tar xf prometheus-${prom_version}.linux-amd64.tar.gz -C /opt/
  ln -sf /opt/prometheus-${prom_version}.linux-amd64 ${pre_path}
}

prom_config() {
  tee >/usr/lib/systemd/system/prometheus.service <<"EOF"
[Unit]
Description=Prometheus Server
Documentation=https://prometheus.io/docs/introduction/overview/
After=network-online.target

[Service]
Type=simple
Restart=on-failure
ExecStart=/opt/prometheus/prometheus \
  --config.file=/opt/prometheus/prometheus.yml \
  --storage.tsdb.path=/opt/prometheus/data \
  --storage.tsdb.retention.time=60d \
  --web.enable-lifecycle

[Install]
WantedBy=multi-user.target
EOF

}
main() {
  [ -f prometheus-${prom_version}.linux-amd64.tar.gz ] || prom_download
  prom_install
  prom_config
  systemctl daemon-reload
  systemctl enable --now prometheus
  if [ $(systemctl is-active prometheus) == "active" ]; then
    echo "prometheus is running,deleting prometheus archive"
    rm -rf ${script_path}/prometheus-${prom_version}.linux-amd64.tar.gz
  else
    echo "prometheus failed,please check!!!"
  fi
}
main